package com.rpp.study.controller;

import com.rpp.study.base.LagouResponse;
import com.rpp.study.config.UserConfig;
import com.rpp.study.feign.FeignCode;
import com.rpp.study.feign.FeignUser;
import com.rpp.study.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @Description
 * @Author rpp
 * @Date 2020/8/28 10:34 下午
 */
@RestController
@RequestMapping(value = "/api/user")
public class UserController implements FeignUser {

    @Autowired
    IUserService userService;

    @Autowired
    FeignCode feignCode;

    /**
     * 注册接⼝，true成功，false失败
     *
     * @param email
     * @param password
     * @param code
     * @return
     */
    @Override
    @PostMapping(value = "/register/{email}/{password}/{code}", consumes = MediaType.APPLICATION_JSON_VALUE)
    public LagouResponse<Boolean> register(@PathVariable("email") String email,
                                           @PathVariable("password") String password,
                                           @PathVariable("code") String code) {

        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();

        if (StringUtils.isBlank(email)) {
            return LagouResponse.error("邮箱不能为空");
        }
        if (StringUtils.isBlank(password)) {
            return LagouResponse.error("密码不能为空");
        }
        if (StringUtils.isBlank(code)) {
            return LagouResponse.error("验证码不能为空");
        }
        // 校验验证码
        LagouResponse<Integer> validate = feignCode.validate(email, code);
        if (!validate.isSuccess()) {
            return LagouResponse.error(validate.getStatusText());
        }
        //注册成功，生成token令牌存入数据库并写到cookie中
        Boolean result = userService.register(email, password, code);
        if (!result) {
            return LagouResponse.error("邮箱已经存在，请登录");
        }
        String token = UUID.randomUUID().toString();
        userService.saveOrUpdateToken(email, token);
        //用户cookie标识
        Cookie cookie = new Cookie(UserConfig.COOKIE_NAME, token);
        cookie.setPath("/");
        cookie.setMaxAge(UserConfig.COOKIE_EXPIRED_TIME_OUT);
        cookie.setDomain("www.test.com");
        response.addCookie(cookie);

        return LagouResponse.success(true);
    }

    /**
     * 是否已注册，根据邮箱判断,true代表已经注册过， false代表尚未注册
     *
     * @param email
     * @return
     */
    @Override
    @GetMapping(value = "/isRegistered/{email}")
    public LagouResponse<Boolean> isRegistered(@PathVariable("email") String email) {
        if (StringUtils.isBlank(email)) {
            return LagouResponse.error("邮箱不能为空");
        }
        return LagouResponse.success(userService.isRegistered(email));
    }

    /**
     * 登录接⼝，验证⽤户名密码合法性，根据⽤户名和密码生成token，token存入数据库，并写入cookie 中
     * 登录成功返回邮箱地址，重定向到欢迎⻚
     *
     * @param email
     * @param password
     * @return
     */
    @Override
    @PostMapping(value = "/login/{email}/{password}", consumes = MediaType.APPLICATION_JSON_VALUE)
    public LagouResponse<String> login(@PathVariable("email") String email,
                                       @PathVariable("password") String password) {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        if (StringUtils.isBlank(email)) {
            return LagouResponse.error("邮箱不能为空");
        }
        if (StringUtils.isBlank(password)) {
            return LagouResponse.error("密码不能为空");
        }
        Boolean result = userService.login(email, password);
        if (!result) {
            return LagouResponse.error("邮箱或者密码不正确");
        }
        //如果登录成功，生成token，token存入数据库，并写⼊入cookie 中
        String token = UUID.randomUUID().toString();
        userService.saveOrUpdateToken(email, token);
        //用户cookie标识
        Cookie cookie = new Cookie(UserConfig.COOKIE_NAME, token);
        cookie.setPath("/");
        cookie.setMaxAge(UserConfig.COOKIE_EXPIRED_TIME_OUT);
        cookie.setDomain("www.test.com");
        response.addCookie(cookie);

        return LagouResponse.success(email);
    }

    /**
     * 根据token查询⽤户登录邮箱接⼝
     *
     * @param token
     * @return
     */
    @Override
    @GetMapping(value = "/info/{token}")
    public LagouResponse<String> info(@PathVariable("token") String token) {
        if (StringUtils.isBlank(token)) {
            return LagouResponse.error("token不存在");
        }
        return LagouResponse.success(userService.info(token));
    }
}
